import requests
import logging
import json
from .config import Config

def detect_language(text: str, default_lang : str = 'en', threshold : float = 0.5) -> str:
    # zh or en?
    scores = {
        'zh': 0.0,
        'jp': 0.0,
        'en': 0.0,
    }
    for c in text:
        if 0x4e00 <= ord(c) <= 0x9fff:
            scores['zh'] += 1
        elif 0x3040 <= ord(c) <= 0x30ff:
            scores['jp'] += 1.5
        elif c.isalpha():
            scores['en'] += 0.1
    threshold += 1
    for k, v in scores.items():
        if all(v > threshold * v2 for k2, v2 in scores.items() if k2 != k):
            return k
    return default_lang

class Translator:
    def __init__(self):
        url = "https://aip.baidubce.com/oauth/2.0/token"
        params = {
            "grant_type": "client_credentials",
            "client_id": Config.auth_api_key,
            "client_secret": Config.auth_secret_key,
        }
        self.token = str(requests.post(url, params=params).json().get("access_token"))
        self.logger = logging.getLogger()

    def _do_translate(self, text: str, from_lang: str = 'auto', to_lang: str = 'zh', terms: list[str] | None = None):
        url = "https://aip.baidubce.com/rpc/2.0/mt/texttrans/v1?access_token=" + self.token
        payload = {
            "from": from_lang,
            "to": to_lang,
            "q": text,
        }
        if terms:
            payload["termIds"] = ','.join(terms)
        payload = json.dumps(payload)
        headers = {
            'Content-Type': 'application/json',
            'Accept': 'application/json',
        }
        response = requests.request("POST", url, headers=headers, data=payload).json()
        if 'error_code' in response and response['error_code'] != 0:
            self.logger.error('API ERROR {}: {}'.format(response['error_code'], response['error_msg']))
        return response

    def translate(self, text: str, from_lang: str = 'auto', to_lang: str = 'zh', terms: list[str] | None = None):
        response = self._do_translate(text, from_lang, to_lang, terms)
        if 'result' not in response:
            return '|ERROR|'
        return '\n'.join(r['dst'] for r in response['result']['trans_result'])

    def chunked_translate(self, texts: list[str], from_lang: str = 'auto', to_lang: str = 'zh'):
        text = '\n'.join(t.replace('\n', ' ').replace('\r', ' ').replace('  ', ' ') for t in texts)
        response = self._do_translate(text, from_lang, to_lang)
        if 'result' not in response:
            return []
        return [(r['dst'], r['src']) for r in response['result']['trans_result']]

if __name__ == '__main__':
    t = Translator()
    print(t.translate('ビジュアルノベル制作チーム「超水道」でシナリオなど担当。\nたまに小説。お仕事はご連絡ください。'))
